import type { RouteRecordRaw } from 'vue-router'

/**
 * @FILENAME:  module.ts
 *  @Description:  // 自动获取路由
 * @Author: ellwood
 * @CreateDate: 2024/10/29 - 22:00
 * @Version: V1.0.0
 */
const layouts = import.meta.glob('../../layouts/**/*.vue')
const pages = import.meta.glob('../../pages/**/*.vue')

function getRoutes() {
  const layoutRoutes = [] as RouteRecordRaw[]
  Object.entries(layouts).forEach(([file, module]) => {
    const route = getRouteByModule(file, module)

    // 获取子路由
    route.children = getChildrenRoutes(route)
    layoutRoutes.push(route)
  })

  return layoutRoutes
}

/**
 * 获取子路由
 * @param layoutRoute 布局路由
 */
function getChildrenRoutes(layoutRoute: RouteRecordRaw) {
  const routes = [] as RouteRecordRaw[]
  Object.entries(pages).forEach(([file, module]) => {
    if (file.includes(`../../pages/${layoutRoute.name as string}`)) {
      const route = getRouteByModule(file, module)
      //   console.log('route===>', route)
      routes.push(route)
    }
  })

  return routes
}

/**
 * 遍历父路由
 * @param file 文件名
 * @param module 模块名
 */
function getRouteByModule(file: string, module: { [key: string]: any }) {
  // const regex = /^(?:\.\.\/){2}layouts(?:\/[^\/]*?)*\/(?<name>[^\/]+)\.vue$/
  //  const regex= /^(?:\.\.\/){2}layouts(?:\/(?<folder>[^\/]+))*\/(?<name>[^\/]+)\.vue$/
  const regex
    = /^(?:\.\.\/){2}(layouts|pages)(?:\/(?<folder>[^\/]+))*\/(?<name>[^\/]+)\.vue$/

  const path = file.replace(regex, '/$<folder>/$<name>')
  // ocnst name = file.match(regex)?.groups?.name
  const name = file.replace(regex, '$<folder>/$<name>')

  const route = {
    name,
    path,
    component: module.default ? module.default : file,
  } as RouteRecordRaw

  // console.log('route===>', route)
  return route
}

// console.log(typeof env.VITE_ROUTER_AUTOLOAD)
// const routes = env.VITE_ROUTER_AUTOLOAD ? getRoutes() : ([] as RouteRecordRaw[])

export default getRoutes
